import javax.swing.tree.TreeNode;

// key-value 模型
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(int key, int value) {
        // write code here

        int index = key % array.length;
        if(array[index] == null){
            array[index] = new Node(key,value);
            size++;
            return;
        }else{
            Node cur = array[index];
            if(cur.key == key){
                cur.value = value;
                return;
            }
            while(cur.next != null){
                cur = cur.next;
                if(cur.key == key){
                    cur.value = value;
                    return;
                }
            }
            cur.next = new Node(key, value);
            size++;
            if(loadFactor() > LOAD_FACTOR){
                resize();
            }
        }
    }


    private void resize() {
        // write code here
        int newLen = array.length*2;
        Node[] newArr = new Node[newLen];
        for(int i = 0;i < array.length;i++){
            Node cur = array[i];
            while(cur != null){
                Node next = cur.next;
                Node newNode = new Node(cur.key, cur.value);
                newNode.next = null;
                int index = cur.key%newLen;
                if(newArr[index] == null){
                    newArr[index] = newNode;
                }else{
                    Node cur1 = newArr[index];
                    while(cur1.next != null){
                        cur1 = cur1.next;
                    }
                    cur1.next = newNode;
                }
                cur = next;
            }
        }
        array = newArr;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        // write code here
        this.array = new Node[DEFAULT_SIZE];
        this.size = 0;
    }


    public int get(int key) {
        // write code here
        int index = key%array.length;
            Node cur = array[index];
            while(cur != null){
                if(cur.key == key){
                    return cur.value;
                }else{
                    cur = cur.next;
                }
            }
        return -1;
    }
}
